# -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 19:37:53 2021

@author: we
"""

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import datetime
import time
import queue     #如果不加载这个模板，pyinstaller打包后，可能无法运行requests模板
import requests
################################################

class FileStorageViewer(QMainWindow):#主窗口

    def __init__(self,UserId):
        super(FileStorageViewer, self).__init__()
        self.resize(900, 700)
        self.setWindowTitle("欢迎使用网盘系统")
        self.UserId = UserId
        self.btn = QPushButton("开始下载", self)
        self.btn.move(30, 50)
        self.show()
    def down_initUI(self,type):
        self.btn.clicked.connect(type.show)
        self.btn.clicked.connect(type.pushButton.click)
        self.show()
################################################
class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        super(Widget, self).__init__(*args, **kwargs)
        layout = QHBoxLayout(self)

        # 增加进度条
        self.textEdit = QTextEdit()  # 创建文本框用于显示
        self.setWindowTitle('下载中...')
        self.progressBar = QProgressBar(self, minimumWidth=400)
        #self.speedshow = QProgressBar(self, minimumWidth=30)
        self.progressBar.setValue(0)
        layout.addWidget(self.progressBar)
        #layout.addWidget(self.speedshow)
        self.lb1 = QLabel(self)
        self.btnPress1 = QPushButton('显示速度')
        layout.addWidget(self.lb1)
        #layout.addWidget(self.btnPress1)
        # 增加下载按钮
        self.pushButton = QPushButton()
        self.btnPress1.clicked.connect(self.btnPress1_clicked)
        
        #self.pushButton.setText("下载")
        #layout.addWidget(self.pushButton)
        
        # 绑定按钮事件
        self.pushButton.clicked.connect(self.on_pushButton_clicked)
        self.btnPress1.click()
        #self.pushButton.click()

        
        
    def btnPress1_clicked(self):
    #以文本的形式输出到多行文本框
        self.onChanged
    # 下载按钮事件
    def on_pushButton_clicked(self):
        set_speed = 1000000#设置速度 单位：byte
        the_url = 'https://dldir1.qq.com/qqtv/TencentVideo10.14.3360.0.exe'
        the_filesize = requests.get(the_url, stream=True).headers['Content-Length']
        the_filepath ="D:/桌面文件/下载程序.exe"#之前的是路径，最后一个/后面是命名
        #the_fileobj = open(the_filepath, 'wb')
        the_fileobj = the_filepath
        #### 创建下载线程
        self.downloadThread = downloadThread(the_url, the_filesize, the_fileobj, set_speed, buffer=10240)
        self.downloadThread.download_proess_signal.connect(self.set_progressbar_value)
        self.downloadThread.download_speed_signal.connect(self.onChanged)
        self.downloadThread.start()



    # 设置进度条
    def set_progressbar_value(self, value):
        self.progressBar.setValue(value)
        if value == 100:
            QMessageBox.information(self, "提示", "下载成功！")
            return
    def onChanged(self,text):
        self.lb1.setText(text)
        self.lb1.adjustSize()

##################################################################
#下载线程
##################################################################
class downloadThread(QThread):
    download_proess_signal = pyqtSignal(int)                        #创建信号
    download_speed_signal = pyqtSignal(str)
    def __init__(self, url, filesize, fileobj, set_speed,buffer):
        super(downloadThread, self).__init__()
        self.url = url
        self.filesize = filesize
        self.fileobj = fileobj
        self.set_speed = set_speed
        self.buffer = buffer
        


    def run(self):
        try:
            proess = 0
            rsp = requests.get(self.url, stream=True)                #流下载模式
            offset = 0
            sped = self.format_size(self.set_speed)
            sped = str(sped)
            time_need = int(self.filesize) / self.set_speed
            time_need_int = int (time_need)
            if time_need >time_need_int:
                time_need = time_need_int + 1
                time_need = int(time_need)
            i = 0
            while i < time_need:
                #推迟1秒
                proess = proess + 100/time_need
                if proess>100:
                    proess = 100
                    self.download_proess_signal.emit(int(proess))        #发送信号
                    break
                self.download_proess_signal.emit(int(proess))        #发送信号
                self.download_speed_signal.emit(sped)
                time.sleep(1) 
                i=i+1
                
            #######################################################################
            #self.fileobj.close()    #关闭文件
            #self.exit(0)            #关闭线程


        except Exception as e:
            print(e)

    def format_size(self,bytes):
        try:
            bytes = float(bytes)
            kb = bytes / 1024
        except:
            print("传入的字节格式不对")
            return "Error"
        if kb >= 1024:
            M = kb / 1024
            if M >= 1024:
                G = M / 1024
                return "%.3fG/s" % (G)
            else:
                return "%.3fM/s" % (M)
        else:
            return "%.3fK/s" % (kb)



####################################
#程序入口
####################################
def main():
    app = QApplication(sys.argv)
    
    a = FileStorageViewer(123)
    down_UI = Widget()
    a.down_initUI(down_UI)
    
    sys.exit(app.exec_())
if __name__ == "__main__":
    main()